function compose (middleware) {
    if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
    for (const fn of middleware) {
      if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
    }
  
    /**
     * @param {Object} context
     * @return {Promise}
     * @api public
     */
  
    return function (context, next) {
      // last called middleware #
      let index = -1
      return dispatch(0)
      function dispatch (i) {
        if (i <= index) return Promise.reject(new Error('next() called multiple times'))
        index = i
        let fn = middleware[i]
        if (i === middleware.length) fn = next
        if (!fn) return Promise.resolve()
        try {
        //   return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
          return new Promise((resolve) => {
            const res  = fn(context, dispatch.bind(null, i + 1))
            resolve(res)
          })
        } catch (err) {
          return Promise.reject(err)
        }
      }
    }
  }

class Koa {
    fnList = []
    ctx = null
    constructor() {
       this.ctx = this
    }
    use(fn) {
        this.fnList.push(fn)
    }

    callback () {
        const fn = compose(this.fnList)

        const handleRequest = (req, res) => {
            const ctx = this.createContext(req, res)
            return this.handleRequest(ctx, fn)
        }

        return handleRequest
    }
    handleRequest (ctx, fnMiddleware) {
        const handleResponse = () => respond(ctx)
        return fnMiddleware(ctx).then(handleResponse).catch(onerror)
    }
    listen (...args) {
        const server = http.createServer((req, res) => {
                const ctx = this.createContext(req, res)
                const handleResponse = () => respond(ctx)
                return fnMiddleware(ctx).then(handleResponse).catch(onerror)
            }
        )
        return server.listen(...args)
    }
}